package cn.itcast.wushangxiantu.Fragment.home;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.Fragment;
import android.app.FragmentTransaction;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;

import com.google.gson.Gson;

import org.greenrobot.eventbus.EventBus;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import cn.itcast.wushangxiantu.BaseAdapter.NongYuanAdapter;
import cn.itcast.wushangxiantu.UserData.HuoDeNumber;
import cn.itcast.wushangxiantu.UserData.User;
import cn.itcast.wushangxiantu.UserData.UserNongTian;
import cn.itcast.wushangxiantu.Activity.Login;
import cn.itcast.wushangxiantu.MessageEvent;
import cn.itcast.wushangxiantu.OkhttpUtil;
import cn.itcast.wushangxiantu.R;
import cn.itcast.wushangxiantu.ToastUtil;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

@SuppressLint("ValidFragment")
public class NongTian extends Fragment implements View.OnClickListener {
    private FragmentTransaction fragmentTransaction;

    private Toast myToast;
    private View view;
    private Context context;
    private TextView tvBuyu;
    private TextView tvCaiKuang;
    private TextView tvFaMu;
    private TextView tvCaiJi;
    private LinearLayout liNongYuan;
    private ListView lvNongYuanXinXi;
    private TextView tvShengJi;
    private RelativeLayout rl;
    private TextView tvBiaoTi;
    private ImageView tvNongYuan4;
    private int id1 = 10;
    private TextView tvGanhuo;
    private boolean Working = false;
    private NeedStopThread thread;
    private static List<UserNongTian> lists;
    NongYuanAdapter nongYuanAdapter;
    private TextView tvChanwu4;
    private View View1;
    private View View2;
    private View View3;
    private View View4;
    private TextView tvLiXian;
    private TextView tvHuoDe;


    public static List<UserNongTian> getLists() {
        return lists;
    }

    public static void setLists(List<UserNongTian> lists) {
        NongTian.lists = lists;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_nong_tian, container, false);
        initView(view);
        return view;
    }

    @SuppressLint("ValidFragment")
    public NongTian(Context context) {
        this.context = context;
    }

    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
    @SuppressLint("ResourceAsColor")
    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tvBuyu:
                id1 = 10;
                changeMenu(0);
                tvBiaoTi.setText("海域");
                tvChanwu4.setText("(盛产珊瑚/龙珠/龟壳/海怪牙齿/咸鱼)");
                tvNongYuan4.setBackground(getResources().getDrawable(R.drawable.nongyuan1));
                break;
            case R.id.tvCaiKuang:
                id1 = 20;
                changeMenu(1);
                tvBiaoTi.setText("矿山");
                tvChanwu4.setText("(盛产黑曜石/铁/黄金/水晶/石头)");
                tvNongYuan4.setBackground(getResources().getDrawable(R.drawable.nongyuan2));
                break;
            case R.id.tvFaMu:
                id1 = 30;
                changeMenu(2);
                tvBiaoTi.setText("林区");
                tvChanwu4.setText("(盛产红木/金丝楠木/紫檀木/橡胶/木头)");
                tvNongYuan4.setBackground(getResources().getDrawable(R.drawable.nongyuan3));
                break;
            case R.id.tvCaiJi:
                id1 = 40;
                changeMenu(3);
                tvBiaoTi.setText("平原");
                tvChanwu4.setText("(盛产布匹/天蚕丝/金丝银线/蚕丝/杂草)");
                tvNongYuan4.setBackground(getResources().getDrawable(R.drawable.nongyuan4));
                break;
            case R.id.tvGanhuo:
                if (!Working) {
                    if (Login.getUser().getDj() >= 20) {
                        ToastUtil.toastLong(context, "正在" + tvBiaoTi.getText() + "挂机中，记得两边都挂机哦");
                    } else {
                        ToastUtil.toastLong(context, "正在" + tvBiaoTi.getText() + "挂机中【二十级可开启两边同时挂机】");
                    }
                    try {
                        tvGanhuo.setText("取消挂机");
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    Working = true;
                    if (thread == null) {
                        thread = new NeedStopThread();
                        thread.start();
                    }
                    if (!thread.isAlive()) {
                        thread = null;
                        thread = new NeedStopThread();
                        thread.start();
                    }
                } else {
                    Working = false;
                    try {
                        Thread.sleep(1000);

                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    tvGanhuo.setText("开始干活");
                }
                break;
            case R.id.tvShengJi:
                if (tvGanhuo.getText().toString().trim().equals("取消挂机")) {
                    ToastUtil.toast(context, "请先取消挂机");
                    return;
                }
                Dialogs();
                break;
            case R.id.tvLiXian:
                ToastUtil.toast(context, "正在设定当前离线区域为" + tvBiaoTi.getText() + "请等待");
                new Thread() {
                    @Override
                    public void run() {
                        try {
                            thread.sleep(2000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        setLiXian();
                    }
                }.start();
                break;
            case R.id.tvHuoDe:
                List<HuoDeNumber>list=new ArrayList<>();
                if (lists.size()!=0){
                    list.add(new HuoDeNumber(lists.get(0).getName(),lists.get(0).getNumber()));
                }
                for (int i = 1; i < lists.size(); i++) {
                    for (int j = 0; j < list.size(); j++) {
                        if (lists.get(i).getName().equals(list.get(j).getName())){
                            list.get(j).setNumber(list.get(j).getNumber()+lists.get(i).getNumber());
                            break;
                        }else if (j==list.size()-1){
                            list.add(new HuoDeNumber(lists.get(i).getName(),lists.get(i).getNumber()));
                            break;
                        }
                    }
                }
                String xinxi="";
                for (int i = 0; i < list.size(); i++) {
                    xinxi+=list.get(i).getName()+"*"+list.get(i).getNumber()+"\n";
                }
                if (xinxi.equals("")){
                    xinxi="无";
                }
                GeneralDialog("掉落详情",xinxi);
                break;
        }
    }
    public void GeneralDialog(String head, String content) {
        /**
         * 普通对话框
         * 1标题
         * 2内容
         */
        AlertDialog dialog;
        AlertDialog.Builder builder = new AlertDialog.Builder(context)
                .setTitle(head)

                .setMessage(content)
                .setNeutralButton("清空", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        lists.clear();
                        nongYuanAdapter.notifyDataSetChanged();
                    }
                })
                .setPositiveButton("确认", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        dialogInterface.dismiss();
                    }
                });
        dialog = builder.create();
        dialog.show();
    }
    private void setLiXian() {
        OkhttpUtil.getRequest(OkhttpUtil.URL_LOG + "userNumber=" + Login.getUser().getUsernumber() + "&need=setlixian" + "&id=" + ((new Random().nextInt(4)+1) + id1), new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.v("lixian1", e.getMessage());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String src = response.body().string();
                Log.v("lixian2", src);
                User user = null;
                try {
                    user = new Gson().fromJson(src, User.class);
                } catch (Exception e) {

                }
                Message message = new Message();
                message.obj = user;
                message.what = 3;
                handler.sendMessage(message);
            }
        });
    }

    private void getNongtianGanHuo() {
        OkhttpUtil.getRequest(OkhttpUtil.URL_LOG + "userNumber=" + Login.getUser().getUsernumber() + "&need=ganhuo" + "&dituID=" + (id1 + new Random().nextInt(4)+1), new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                try {
                    Log.v("nongtianganhuo1", e.getMessage());
                }catch (Exception e1){

                }
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String src = response.body().string();
                Log.v("nongtianganhuo2", src);
                UserNongTian user = null;
                try {
                    user = new Gson().fromJson(src, UserNongTian.class);
                } catch (Exception e) {

                }
                Message message = new Message();
                message.obj = user;
                message.what = 1;
                handler.sendMessage(message);
            }
        });
    }

    Handler handler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(@NonNull Message message) {
            if (message.what == 1) {
                UserNongTian user = (UserNongTian) message.obj;
                if (user != null) {
                    if (user != null && user.getStw().equals("Ok")) {
                        user.setDiquName(tvBiaoTi.getText().toString().trim());
                        if (user.getName().equals("石魂")) {
                            MessageEvent messageEvent = new MessageEvent("xinxi");
                            messageEvent.setContent("恭喜玩家" + Login.getUser().getName() + "在人间挂机获得石魂"+user.getNumber()+"枚");
                            EventBus.getDefault().post(messageEvent);
                        }
                        lists.add(user);
                        if (nongYuanAdapter == null) {
                            nongYuanAdapter = new NongYuanAdapter(context);
                        }
                        nongYuanAdapter.notifyDataSetChanged();
                    } else if (user == null) {
                        ToastUtil.toast(context, "被其他人玩家抢先一步");
                    } else {
                        ToastUtil.toast(context, user.getStw());
//                    //停止线程
//                    Working = false;
//                    try {
//                        Thread.sleep(1000);
//                        if (thread != null) {
//                            thread = null;
//                        }
//                    } catch (InterruptedException e) {
//                        e.printStackTrace();
//                    }
//                    tvGanhuo.setText("开始干活");
                    }
                } else {
                    ToastUtil.toast(context, "服务器坏了");
                }
            } else if (message.what == 2) {
                User user = (User) message.obj;
                if (user != null) {
                    if (user.getStw().equals("Yes")) {
                        ToastUtil.toast(context, "升级成功");
                        Login.getUser().setHy(user.getHy());
                        Login.getUser().setKq(user.getKq());
                        Login.getUser().setPy(user.getPy());
                        Login.getUser().setLq(user.getLq());
                        initView(view);
                    } else {
                        ToastUtil.toast(context, user.getStw());
                    }
                } else {
                    ToastUtil.toast(context, "服务器坏了");
                }
            } else if (message.what == 3) {
                User user = (User) message.obj;
                if (user != null) {
                    ToastUtil.toast(context, user.getStw());
                } else {
                    ToastUtil.toast(context, "服务器坏掉了");
                }
            }
            return false;
        }
    });

    public void changeMenu(int num) {
        View1.setVisibility(View.INVISIBLE);
        View2.setVisibility(View.INVISIBLE);
        View3.setVisibility(View.INVISIBLE);
        View4.setVisibility(View.INVISIBLE);

        switch (num) {
            case 0:
                View1.setVisibility(View.VISIBLE);
                break;
            case 1:
                View2.setVisibility(View.VISIBLE);
                break;
            case 2:
                View3.setVisibility(View.VISIBLE);
                break;
            case 3:
                View4.setVisibility(View.VISIBLE);
                break;
        }
    }



    private void initView(View view) {
        lists = new ArrayList<>();
        tvBuyu = (TextView) view.findViewById(R.id.tvBuyu);
        tvCaiKuang = (TextView) view.findViewById(R.id.tvCaiKuang);
        tvFaMu = (TextView) view.findViewById(R.id.tvFaMu);
        tvCaiJi = (TextView) view.findViewById(R.id.tvCaiJi);
        liNongYuan = (LinearLayout) view.findViewById(R.id.liNongYuan);
        lvNongYuanXinXi = (ListView) view.findViewById(R.id.lvNongYuanXinXi);
        tvShengJi = (TextView) view.findViewById(R.id.tvShengJi);
        rl = (RelativeLayout) view.findViewById(R.id.rl);
        tvGanhuo = (TextView) view.findViewById(R.id.tvGanhuo);

        tvBuyu.setText("LV:" + Login.getUser().getHy() + " 钓鱼");
        tvCaiKuang.setText("LV:" + Login.getUser().getKq() + " 挖矿");
        tvFaMu.setText("LV:" + Login.getUser().getLq() + " 伐木");
        tvCaiJi.setText("LV:" + Login.getUser().getPy() + " 采集");

        tvBuyu.setOnClickListener(this);
        tvFaMu.setOnClickListener(this);
        tvCaiJi.setOnClickListener(this);
        tvCaiKuang.setOnClickListener(this);
        tvGanhuo.setOnClickListener(this);
        tvShengJi.setOnClickListener(this);


        tvBiaoTi = (TextView) view.findViewById(R.id.tvBiaoTi);
        tvBiaoTi.setOnClickListener(this);
        tvNongYuan4 = (ImageView) view.findViewById(R.id.ivNongYuan4);
        tvGanhuo = (TextView) view.findViewById(R.id.tvGanhuo);
        tvGanhuo.setOnClickListener(this);
        if (nongYuanAdapter == null) {
            nongYuanAdapter = new NongYuanAdapter(context);
        }
        lvNongYuanXinXi.setAdapter(nongYuanAdapter);

        tvChanwu4 = (TextView) view.findViewById(R.id.tvChanwu4);
        tvChanwu4.setOnClickListener(this);
        View1 = (View) view.findViewById(R.id.View1);
        View2 = (View) view.findViewById(R.id.View2);
        View3 = (View) view.findViewById(R.id.View3);
        View4 = (View) view.findViewById(R.id.View4);
        tvLiXian = (TextView) view.findViewById(R.id.tvLiXian);
        tvLiXian.setOnClickListener(this);
        tvHuoDe = (TextView) view.findViewById(R.id.tvHuoDe);
        tvHuoDe.setOnClickListener(this);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (thread != null) {
            thread.interrupt();
            Working = false;
            thread = null;
        }
    }

    public void Dialogs() {
        final int[] num = {0};
        AlertDialog dialog;
        AlertDialog.Builder builder = new AlertDialog.Builder(context)
                .setTitle("选择升级")
                .setSingleChoiceItems(new String[]{"钓鱼", "挖矿", "伐木", "采集"}, 0, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        num[0] = i;
                    }
                })
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        dialogInterface.dismiss();
                        Dialog(num[0]);
                    }
                });
        dialog = builder.create();
        dialog.show();
    }

    public void getShengji(String diqu) {
        OkhttpUtil.getRequest(OkhttpUtil.URL_LOG + "userName=" + Login.getUser().getUsernumber() + "&passWord=" + Login.getUser().getPassword()
                + "&need=shengji" + "&diqu=" + diqu + "&banben=" + Login.getVerName(context), new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.v("NongtianShengji1", e.getMessage());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String src = response.body().string();
                Log.v("NongtianShengji2", src);
                User user = null;
                try {
                    user = new Gson().fromJson(src, User.class);
                } catch (Exception e) {

                }
                Message message = new Message();
                message.obj = user;
                message.what = 2;
                handler.sendMessage(message);
            }
        });
    }


    public void Dialog(int num) {
        String content = "";
        String diqu = "";
        int number = 0;
        switch (num) {
            case 0:
                number = (Login.getUser().getHy() * 10);
                diqu = "hy";
                content = "珊瑚*" + number + "\t海怪牙齿*" + number + "\n" +
                        "龙珠*" + number + "\t龟壳*" + number + "\n";
                break;
            case 1:
                number = (Login.getUser().getKq() * 10);
                diqu = "kq";
                content = "铁*" + number + "\t水晶*" + number + "\n" +
                        "黄金*" + number + "\t黑曜石*" + number + "\n";
                break;
            case 2:
                number = (Login.getUser().getLq() * 10);
                diqu = "lq";
                content = "橡胶*" + number + "\t红木*" + number + "\n" +
                        "紫檀木*" + number + "\t金丝楠木*" + number + "\n";
                break;
            case 3:
                number = (Login.getUser().getPy() * 10);
                diqu = "py";
                content = "布匹*" + number + "\t蚕丝*" + number + "\n" +
                        "天蚕丝*" + number + "\t金丝银线*" + number + "\n";
                break;
        }
        /**
         * 普通对话框
         * 1标题
         * 2内容
         */
        AlertDialog dialog;
        final String finalDiqu = diqu;
        AlertDialog.Builder builder = new AlertDialog.Builder(context)
                .setTitle("预计消耗")
                .setMessage(content)
                .setPositiveButton("确认", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        getShengji(finalDiqu);
                        dialogInterface.dismiss();
                    }
                });
        dialog = builder.create();
        dialog.show();

    }

    class NeedStopThread extends Thread {
        @Override
        public void run() {
            while (Working) {
                try {
                    sleep(5000);
                    if (Working) {
                        getNongtianGanHuo();
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

        }
    }
}